package com.caocaog.market.pay.syb.service.impl;

import com.caocaog.market.pay.syb.config.SybConfig;
import com.caocaog.market.pay.syb.dto.SybDto;
import com.caocaog.market.pay.syb.service.ISybPayService;
import com.caocaog.market.pay.syb.utils.SybPay;
import com.caocaog.market.pay.syb.utils.SybUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Map;
import java.util.TreeMap;

@Slf4j
@Service
public class SybPayServiceImpl  implements ISybPayService {


	@Resource
	SybPay sybPay;

	@Value(value = "${syb.wxAppId}")
	private String wxAppId;
	@Value(value = "${syb.aliAppId}")
	private String aliAppId;

	/**
	 * 统一支付
	 */
	@Override
	public Map<String,String> pay(SybDto sybDto) throws Exception{

		if(sybDto.getPayType().equals("W02")) {

			sybDto.setSubAppId(wxAppId);
		}else if(sybDto.getPayType().equals("A01")){
			sybDto.setSubAppId(aliAppId);
		}
		return sybPay.pay(sybDto,"/customerSybNotify");

	}

	/**
	 *交易撤销
	 */
	@Override
	public Map<String,String> cancel(SybDto sybDto) throws Exception{

		return sybPay.cancel(sybDto);
	}

	/**
	 *交易退款
	 */
	@Override
	public Map<String,String> refund(SybDto sybDto) throws Exception{
		return sybPay.refund(sybDto);
	}

	/**
	 *交易查询
	 */
	@Override
	public Map<String,String> query(SybDto sybDto) throws Exception{
		return sybPay.query(sybDto);
	}

	/**
	 *交易关闭
	 */
	@Override
	public Map<String,String> close(SybDto sybDto) throws Exception{
		return sybPay.close(sybDto);
	}


	@SuppressWarnings({ "rawtypes", "unchecked" })
	public static Map<String,String> handleResult(String result) throws Exception{
		System.out.println("ret:"+result);
		Map map = SybUtil.json2Obj(result, Map.class);
		if(map == null){
			throw new Exception("返回数据错误");
		}
		if("SUCCESS".equals(map.get("retcode"))){
			TreeMap tmap = new TreeMap();
			tmap.putAll(map);
			String appkey = "";
			if(SybConfig.SIGN_TYPE.equals("RSA")) {
				appkey = SybConfig.SYB_RSATLPUBKEY;
			}
			else if(SybConfig.SIGN_TYPE.equals("SM2")) {
				appkey = SybConfig.SYB_SM2TLPUBKEY;
			}
			else {
				appkey = SybConfig.SYB_MD5_APPKEY;
			}

			if(SybUtil.validSign(tmap, appkey, SybConfig.SIGN_TYPE)){
				System.out.println("签名成功");
				return map;
			}else{
				throw new Exception("验证签名失败");
			}

		}else{
			throw new Exception(map.get("retmsg").toString());
		}
	}

	@Override
	public Map<String, String> scanPay(SybDto sybDto) throws Exception{
		return sybPay.scanPay(sybDto);
	}
}
